#!/usr/bin/python
# -*- coding: utf-8 -*-

#TODO
#fix atom summaries

import os, sys

import gtk
import glib
import cairo
import time
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet import reactor
from twisted.web.client import getPage
import html2text
import logging, logging.handlers
from django.utils.translation import ugettext_lazy as _

#clean these later
from RSS import *
from properties import *
from fbevents import *
from feedsparse import *
#from getlogo import *

#temporary
import webbrowser

#Test
DIR_USER = os.environ['HOME'] + '/.feedbar'
DIR_USER1 = '/usr/share/feedbar'
DIR_USER2 = '/usr/local/share/feedbar'

class Bar:

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_title("Feedbar")
        self.window.resize(gtk.gdk.screen_width(), 30)
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
        self.window.move(0, gtk.gdk.screen_height()-55)
        self.window.show()
        self.window.window.property_change("_NET_WM_STRUT", "CARDINAL", 32, 
            gtk.gdk.PROP_MODE_REPLACE, [0, 0, 0, 55])
        self.bar()

        # show gtk icons
        self.settings = gtk.settings_get_default()
        self.settings.set_property("gtk-button-images", True)


        self.window.connect("destroy", gtk.main_quit)

#        self.window.set_tooltip_text("The current feed from {0}".format(self.feedtitle))

        self.window.connect("button-press-event", self._on_button_press_event)
        self.window.connect("scroll-event", self.scroll_event)
        self.window.connect("enter-notify-event", self.enter_notify)
        self.window.connect("leave-notify-event", self.leave_notify)


        self.window.props.has_tooltip = True
        self.window.connect("query-tooltip", self.query_tooltip_cb)

        self.window.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self.task_done = False

        self.collapsed = False
        self.formatting()

        self.optionsavail = {'Feed': (RSSdraw, RSSdownload)}

        self.feeds = getfeeds()

        for seq, info in enumerate(self.feeds.values()):
#            (self.type[seq], feed_title, feed_link, self.feedmax[seq], self.RtL[seq], self.pango_enabled[seq]) = info
            feed_type = self.feeds[seq]['feed_type']
            self.optionsavail[feed_type][1](self, self.feeds[seq]['feed_link'], seq)
#        glib.timeout_add_seconds(120, self.optionsavail[self.type[seq]][1], self, feed_link, seq)

            #test <<<<>>>>>>
            self.draw[seq] = self.optionsavail[feed_type][0]
        glib.timeout_add_seconds(300, self.download_timer)

        if not self.feeds[self.feedseq]['RtL']:
            self.xLocation = self.w + 100
        elif self.feeds[self.feedseq]['RtL']:
            self.xLocation = 0


        self.darea = gtk.DrawingArea()
        self.darea.connect("expose-event", self.expose, self.draw[self.feedseq])
        self.window.add(self.darea)

        glib.timeout_add(30, self.on_timer)
        
        self.window.show_all()


    def bar(self):
        self.statusIcon = gtk.StatusIcon()
        self.statusIcon.set_from_file(DIR_USER1 + "/images/feedbar.png")
        self.statusIcon.set_visible(True)
        self.statusIcon.set_tooltip("Feedbar")
        self.menu = gtk.Menu()
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_PROPERTIES)
        self.menuItem.connect('activate', self.execute_cb, self.statusIcon)
        self.menu.append(self.menuItem)
        self.menuItem = gtk.ImageMenuItem(stock_id='Official Site')
        self.menuItem.connect('activate', self.opensite_cb, self.statusIcon)
        self.menu.append(self.menuItem)
        separator = gtk.MenuItem()
        self.menu.append(separator)
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menuItem.connect('activate', self.quit_cb, self.statusIcon)
        self.menu.append(self.menuItem)
        self.statusIcon.connect('popup-menu', self.popup_menu_cb, self.menu)
        self.statusIcon.set_visible(1)
        self.statusIcon.connect("button-press-event", self.collapse_cb)


    def on_timer(self):
        if not self.timer: return False
    
#        if not self.movespeed == 0:
        if not self.collapsed:
            self.darea.queue_draw()
        return True

    def download_timer(self):
        for seq, info in enumerate(self.feeds.values()):
            feed_type = self.feeds[seq]['feed_type']
            self.optionsavail[feed_type][1](self, self.feeds[seq]['feed_link'], seq)
        return True


    def formatting(self):
        self.feedseq = 0
        self.font = "MgOpen Modata"
        self.timer = True
        self.movespeed = 3
        self.initial_moves = False
        self.width = {}
        self.height = {}
        self.height_diff = {}
        self.location = {}
        self.inner_logo_location = {}
        self.out = {}
        self.feedcontent = {}
        self.logo = {}
        self.draw = {}
        self.feedrange = {}
        self.layout = {}
        self.h = self.window.allocation.height
        self.w = self.window.allocation.width
        self.pointer_on_bar = False
        self.pointer_on_title = True
        self.pointer_on_rest = False



    def expose(self, widget, event, feed_type):
        cr = widget.window.cairo_create()

        # main bar
        if not self.feeds[self.feedseq]['RtL']: # direction of movement
            self.xLocation = self.xLocation - self.movespeed
        elif self.feeds[self.feedseq]['RtL']:
            self.xLocation = self.xLocation + self.movespeed

        crlinear = cairo.LinearGradient(0.0, 0.0,  0.0, 30)
#        crlinear.add_color_stop_rgba (0.3, 0.998, 0.294, 0.176, 1)
#        crlinear.add_color_stop_rgba (1, 0.776470588, 0.062745098, 0.039215686, 1)
        crlinear.add_color_stop_rgba (0.6, 0.247, 0.470588235, 0.662745098, 1)
        crlinear.add_color_stop_rgba (1, 0.184313725, 0.345098039, 0.50, 1)
        cr.set_source(crlinear)
        cr.rectangle((self.w/7) - ((self.w/7)/13), 0, self.w, self.h)

        cr.fill()


        cr.select_font_face(self.font, cairo.FONT_SLANT_NORMAL)

        cr.set_source_rgb(1, 1, 1)


        #Draw here
        feed_type(self, self.window, cr)
            

        # title part
#        cr.rectangle (0,0,(self.w/7),self.h)
        cr.set_source_rgba(0.9, 0.9, 0.9, 1)
        cr.move_to(0, self.h)
        cr.line_to(0, 0)
        cr.line_to((self.w/7) - ((self.w/7)/13), 0)
        cr.curve_to((self.w/7), 5, (self.w/7), 25, (self.w/7), 30)
        cr.close_path()
        cr.fill()

        crlinear = cairo.LinearGradient((self.w/7), 0.0,  (self.w/7), 30)
        crlinear.add_color_stop_rgba (0.6, 0.84, 0.84, 0.84, 1)
        crlinear.add_color_stop_rgba (1, 0.72, 0.72, 0.72, 1)
        cr.set_source(crlinear)
        cr.move_to(30, self.h)
        cr.curve_to(80, 20, 80, 10, (self.w/7) - ((self.w/7)/13), 0)
        cr.curve_to((self.w/7), 5, (self.w/7), 25, (self.w/7), 30)
#        cr.line_to((self.w/7), self.h)
        cr.close_path()

        cr.fill()

#        cr.save()


        # drawing image (comsumes a bit more cpu)

        try:
            surface = self.surface
            logo_height = self.logo_height
            logo_width = self.logo_width
            measure = self.measure
            logo_opt_h = self.logo_opt_h
        except AttributeError:
            surface = cairo.ImageSurface.create_from_png(DIR_USER1 + "/images/title_logo.png")
            logo_height = float(surface.get_height())
            logo_width = float(surface.get_width())
            new_height = self.h * 0.8
            measure = new_height / logo_height
            logo_opt_h = (self.h/2 - ((logo_height)*measure)/2)/measure
            self.surface = surface
            self.logo_height = logo_height
            self.logo_width = logo_width
            self.measure = measure
            self.logo_opt_h = logo_opt_h
#            print "image from png"
            

        cr.scale(measure, measure)
        cr.rectangle (20/measure, logo_opt_h, logo_width, logo_height)
        cr.set_source_surface(surface, 20/measure, logo_opt_h)
        cr.fill()

#        cr.restore()



#        cr.set_source_rgba(0.776470588, 0.062745098, 0.039215686, 1)
#        cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL)
#        cr.set_font_size(17)
#        cr.move_to(50, self.h/1.4)
#        cr.show_text("Latest News")

        try:
            # moving to next feed
            if not self.feeds[self.feedseq]['RtL']:
                m_condition = self.location[self.feedrange[self.feedseq]-1] <= self.stoppoint + 100
            elif self.feeds[self.feedseq]['RtL']:
                m_condition = self.location[len(self.feedcontent[self.feedseq]['entries'])-1] >= self.w + 100


            if m_condition:
                self.nextfeedseq = self.feedseq + 1
                if not self.nextfeedseq in self.feeds:
                    self.feedseq = 0
                else:
                    self.feedseq = self.nextfeedseq

                parse(self, self.out[self.feedseq], self.feedseq)

                # clearing cache
                del self.font_size
                del self.inner_surface
                if not self.feeds[self.feedseq]['pango']:
                    self.width = {}
                if self.feeds[self.feedseq]['pango']:
                    self.layout = {}
#                for idx in range(len(self.feedcontent[self.feedseq]['entries'])):
#                    measurewidth(self, cr, idx)


                if not self.feeds[self.feedseq]['RtL']: # direction of movement
                    self.xLocation = self.w + 100
                elif self.feeds[self.feedseq]['RtL']: # direction of movement
                    self.xLocation = 0

#                print "next feed" , self.feedseq

        except KeyError:
#            print "Loading, current sequence", self.feedseq, "While moving to next feed"
            if not self.feeds[self.feedseq]['RtL']:
                self.xLocation = self.w + 100
            elif self.feeds[self.feedseq]['RtL']:
                self.xLocation = 0


#        for l in range(len(self.feedlinks)):
#            feedname = self.feedlinks.keys()[l]
#            vars()[feedname] = feed(self.feedlinks.values()[l])


    def _on_button_press_event(self, widget, event):
        on_click(self, widget, event)

    def scroll_event(self, button, event):
        if event.direction == gtk.gdk.SCROLL_UP: direction=1
        else: direction=-1

        if self.pointer_on_title == True:
            if direction == 1:
                self.movespeed = self.movespeed + 0.5
            elif direction == -1:
                self.movespeed = self.movespeed - 0.5

    def enter_notify(self, widget, event):
        self.pointer = self.window.get_pointer()
#        print "Enter bar", self.pointer
        self.pointer_on_bar = True
        if  (0 <= self.pointer[0] <= (self.w/7)) and (0 <= self.pointer[1] <= self.h):
#            print "On Title"
            self.pointer_on_title = True
            self.pointer_on_rest = False
        elif self.pointer[0] >= (self.w/7) and (0 <= self.pointer[1] <= self.h):
#            print "On Rest"
            self.pointer_on_rest = True
            self.pointer_on_title = False
            if not self.movespeed == 0:
                self.movespeedbef = self.movespeed
                self.movespeed = 0


    #problem
    def leave_notify(self, widget, event):
        self.pointer = self.window.get_pointer()
#        print self.pointer
        #TEMP SOL
        if not (0 < self.pointer[0] < self.w) or not (0 < self.pointer[1] < self.h):
            try:
                self.movespeed = self.movespeedbef
                del self.movespeedbef
            except AttributeError:
                pass
#            print "leave"
            self.pointer_on_bar = False
            self.pointer_on_rest = False
            self.pointer_on_title = False



    def query_tooltip_cb(self, widget, x, y, keyboard_tip, tooltip):
        if self.pointer_on_rest == True:
            try:
                for idx in range(self.feedrange[self.feedseq]):
                    if self.location[idx] < x < (self.location[idx] + self.width[idx]):
                        tip = html2text.html2text(self.feedcontent[self.feedseq].entries[idx].summary)
                        self.window.set_tooltip_text(tip)
                        break

                    elif self.inner_logo_location[idx] < x < (self.inner_logo_location[idx] + self.inner_logo_width) and not idx == (self.feedrange[self.feedseq]):
                        self.window.set_tooltip_text(self.feedcontent[self.feedseq].feed.title)
                        break
            except KeyError:
                #careful here
                pass

        if self.pointer_on_title == True:
            self.window.set_tooltip_text("Statistics here")



    #imagemenu functions

    def execute_cb(self, widget, event):
        Properties().main()

    def opensite_cb(self, widget, event):
        webbrowser.open('http://www.feedbar.org')

    def quit_cb(self, widget, data = None):
        gtk.main_quit()
        exit()


    def popup_menu_cb(self, widget, button, time, data = None):
        if button == 3:
            if data:
                data.show_all()
                data.popup(None, None, gtk.status_icon_position_menu,
                           3, time, self.statusIcon)

    def collapse_cb(self, widget, event):
        if event.button == 1:
            if not self.collapsed:
                self.collapsed = True
                self.window.hide()
            elif self.collapsed:
                self.collapsed = False
                self.window.set_position(gtk.WIN_POS_CENTER)
                self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
                self.window.move(0, gtk.gdk.screen_height()-55)
                self.window.show()


    def main(self):
        gtk.main()


if __name__ == "__main__":

    bar = Bar()
    reactor.run()
